package com.neuronbit.businessflow.flow.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * The type Jar file util.
 */
public final class JarFileUtil {

    private JarFileUtil() {
        throw new UnsupportedOperationException("Utility Class");
    }

    /**
     * Unzip jar file.
     *
     * @param jarFilePath the jar file path
     * @param destDir     the dest dir
     * @throws IOException the io exception
     */
    public static void unzipJarFile(File jarFilePath, File destDir) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(jarFilePath))) {
            ZipEntry entry = zipIn.getNextEntry();
            while (entry != null) {
                File filePath = destDir.toPath().resolve(entry.getName()).toFile();
                if (!entry.isDirectory()) {
                    extractFile(zipIn, filePath);
                } else {
                    filePath.mkdirs();
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }
        }
    }

    private static void extractFile(ZipInputStream zipIn, File filePath) throws IOException {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
            byte[] bytesIn = new byte[4096];
            int read;
            while ((read = zipIn.read(bytesIn)) != -1) {
                bos.write(bytesIn, 0, read);
            }
        }
    }
}
